import React, { useState, useEffect, useCallback } from 'react';
import {
  StyleSheet,
  View,
  TextInput,
  TouchableOpacity,
  Text,
  FlatList,
  ActivityIndicator,
  Alert
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import * as rootNavigation from '@/utils/rootNavigation';
import { connect } from 'react-redux';
import { useTranslation } from 'react-i18next';
import CardComponent from '@/components/CardComponent';
import RecordItemList from '@/components/RecordItemList';
import SearchBox from '@/components/SearchBox';
import draft from '@/assets/images/draft.png';
import StorageUtils from '@/utils/storageUtils';
import { APP_CODE as appCode } from '../../../app.json';
import { getProcessInstancePageList, addProcessTask, deleteProcessDraft } from '@/apis/api';

let SetDetail = ({ navigation }) => {
  const { t } = useTranslation();
  // const [dialogVisible, setDialogVisible] = useState(false);
  const [searchQuery, setSearchQuery] = useState('');
  const [cardList, setCardList] = useState([]);
  const [loading, setLoading] = useState(false);
  const [loadingMore, setLoadingMore] = useState(false);
  const [pagination, setPagination] = useState({
    pageNo: 1,
    pageSize: 10,
    total: 0,
    hasMore: true
  });

  // 防抖搜索函数
  const debounce = (func, delay) => {
    let timer;
    return function (...args) {
      clearTimeout(timer);
      timer = setTimeout(() => func.apply(this, args), delay);
    };
  };

  // 获取数据
  const fetchData = async (isLoadMore = false) => {
    if ((!isLoadMore && loading) || (isLoadMore && !pagination.hasMore)) return;

    const currentPage = isLoadMore ? pagination.pageNo + 1 : 1;

    try {
      isLoadMore ? setLoadingMore(true) : setLoading(true);

      const auth = await StorageUtils.getItem('auth');
      const params = {
        pageNum: currentPage,
        pageSize: pagination.pageSize,
        name: searchQuery,
        // namespace: appCode,
        creatorId: auth?.user_id || '',
        status: -1
      };

      const res = await getProcessInstancePageList(params);

      setCardList(prev =>
        isLoadMore ? [...prev, ...res.data.records] : res.data.records
      );

      setPagination({
        ...pagination,
        pageNo: currentPage,
        total: res.data.total,
        hasMore: res.data.records.length >= pagination.pageSize
      });
    } catch (error) {
      Alert.alert(t('sys_error'), error.message);
    } finally {
      isLoadMore ? setLoadingMore(false) : setLoading(false);
    }
  };

  // 初始化数据
  useEffect(() => {
    // fetchData();
    navigation.setOptions({
      headerShown: true,
      headerBackVisible: true,
    });
  }, []);

  // 搜索防抖处理
  useEffect(() => {
    const debouncedSearch = debounce(() => {
      setPagination(prev => ({ ...prev, pageNo: 1 }));
      fetchData();
    }, 500);

    debouncedSearch();
    return () => debouncedSearch.cancel?.();
  }, [searchQuery]);

  // 加载更多
  const handleLoadMore = () => {
    if (pagination.hasMore && !loadingMore) {
      fetchData(true);
    }
  };

  const handleDelete = async (cardItem) => {
    try {
      const result: any = await deleteProcessDraft(cardItem?.id);
      if (result?.code == 200) {
        await fetchData();
      }
    } catch (error) {
      Alert.alert('删除失败', error.message);
    }
  };

  const handleAction = async (cardItem, actionType) => {
    if (actionType === '编辑') {
      const res = await addProcessTask(cardItem.flowCode)
      const queryString = `?path=${res?.data?.formCode}&name=${res?.data?.name}&flowCode=${res?.data?.code}&flowInstanceCode=${cardItem?.id}&type=form&actionType=myDraf`;
      rootNavigation.replace('ProessForm', {
        query: queryString,
        appCode: cardItem?.namespaceCode
      });
    } else if (actionType === '删除') {
      // 删除
      Alert.alert(
        t('sys_tip'),
        t('sys_confirmDel'),
        [
          {
            text: t('sys_cancel'),
            style: 'cancel',
          },
          {
            text: t('sys_confirm'),
            onPress: () => handleDelete(cardItem),
            style: 'destructive',
          },
        ],
        { cancelable: true }
      );

    }
  };

  // 渲染底部加载指示器
  const renderFooter = () => {
    if (!loadingMore) return null;
    return (
      <View style={styles.footer}>
        <ActivityIndicator size="small" color="#2a50d7" />
        <Text style={styles.loadingText}>{t('sys_loading')}</Text>
      </View>
    );
  };

  // 渲染空状态
  const renderEmpty = () => (
    <View style={styles.emptyContainer}>
      <Text style={styles.emptyText}>{t('sys_no_data')}</Text>
    </View>
  );

  return (
    <View style={styles.container}>
      {/* 搜索栏 */}
      <View style={styles.search}>
        <View style={styles.searchContainer}>
          <Icon name="search" size={20} color="#999" style={styles.searchIcon} />
          <TextInput
            style={styles.searchInput}
            placeholder={t('sys_select')}
            placeholderTextColor="#999"
            value={searchQuery}
            onChangeText={setSearchQuery}
            autoFocus={Platform.OS === 'android'}
          />
          {searchQuery.length > 0 && (
            <TouchableOpacity
              style={styles.clearButton}
              onPress={() => setSearchQuery('')}
            >
              <Icon name="close" size={18} color="#999" />
            </TouchableOpacity>
          )}
        </View>
        {/* <SearchBox /> */}
      </View>

      {/* 卡片列表 */}
      {loading && !loadingMore ? (
        <View style={styles.loadingContainer}>
          <ActivityIndicator size="large" color="#2a50d7" />
        </View>
      ) : (
        <FlatList
          data={cardList}
          keyExtractor={item => item.id}
          renderItem={({ item }) => (
            <CardComponent
              title={item.name}
              timeText={`更新时间：${item?.modifyTime}`}
              content={
                <View>
                  <View style={styles.card_row}>
                    <Text style={styles.card_label}>创建时间</Text>
                    <Text style={styles.card_text}>{item.createTime}</Text>
                  </View>
                </View>
              }
              icon={draft}
              onLeftPress={() => handleAction(item, '编辑')}
              onRightPress={() => handleAction(item, '删除')}
              leftButtonText={t('sys_edit')}
              rightButtonText={t('sys_del')}
            />
          )}
          contentContainerStyle={styles.listContainer}
          ItemSeparatorComponent={() => <View style={styles.separator} />}
          ListFooterComponent={renderFooter}
          ListEmptyComponent={renderEmpty}
          onEndReached={handleLoadMore}
          onEndReachedThreshold={0.2}
          removeClippedSubviews={true}
          initialNumToRender={5}
          windowSize={10}
        />
      )}

      {/* <RecordItemList
        visible={dialogVisible}
        processData={{ flowInstanceCode: '123' }}
        onClose={(visible) => setDialogVisible(visible)}
      /> */}
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#F3F4F8',
  },
  search: {
    backgroundColor: '#fff',
    padding: 5,
    flexDirection: 'row',
    alignItems: 'center',
  },
  searchContainer: {
    flex: 1,
    flexDirection: 'row',
    alignItems: 'center',
    backgroundColor: '#f5f5f5',
    borderRadius: 44,
    marginHorizontal: 10,
    marginVertical: 8,
    paddingHorizontal: 12,
    height: 40,
  },
  searchIcon: {
    marginRight: 8,
  },
  searchInput: {
    flex: 1,
    fontSize: 16,
    color: '#333',
    paddingVertical: 0,
  },
  clearButton: {
    padding: 4,
    marginLeft: 8,
  },
  listContainer: {
    padding: 16,
    paddingBottom: 28,
    flexGrow: 1,
  },
  separator: {
    height: 16,
  },
  footer: {
    padding: 10,
    alignItems: 'center',
  },
  loadingText: {
    marginTop: 5,
    color: '#666',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    padding: 20,
  },
  emptyText: {
    color: '#999',
    fontSize: 16,
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
  },
  card_row: {
    display: 'flex',
    flexDirection: 'row',
    gap: 10,
    // justifyContent: 'center',
    alignItems: 'center',
  },
  card_label: {
    width: 60,
    // marginRight: 15
  },
  card_text: {
    flex: 1,
    color: '#000',
    // marginLeft: 15,
  }
});

export default connect()(SetDetail);